#1,sku image管理
from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.good import sku_images_serializer
from goods.models import SKUImage, SKU
from meiduo_admin.my_paginate import MyPageNumberPagination
from rest_framework.response import Response
from django.conf import settings

#1,sku image管理
class SKUImageViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = sku_images_serializer.SKUImageSerializer
    queryset = SKUImage.objects.order_by("id").all()

    # 1,重写createModelXin的create方法,上传图片
    def create(self, request, *args, **kwargs):
        # 1.获取参数
        sku_id = request.data.get('sku')
        image = request.FILES.get('image')

        # 2.校验参数
        if not all([sku_id,image]):
            return Response(status=400)

        # 3.数据入库（fdfs,数据库）
        #上传照片
        client = Fdfs_client(settings.BASE_CONFIG)
        result = client.upload_by_buffer(image.read())
        if result.get("Status") != "Uplosd successed.":
            return Response(status=400)

        image_url = result.get("Remote file_id")


        # 4.入库图片
        # 入库图片
        SKUImage.objects.create (image=image_url, sku_id=sku_id)
        SKU.objects.filter (id=sku_id, default_image_url='').update (default_image_url=image_url)

        # 4,返回响应
        return Response (status=201)



    # 2.重写update方法，修改图片
    def upload(self,request,*args,**kwargs):
        # 1.获取参数
        sku_id = request.data.get('sku')
        image = request.FILES.get('image')
        sku_image = self.get_object()

        # 2.校验参数
        # 上传照片
        client = Fdfs_client(settings.BASE_CONFIG)
        result = client.upload_by_buffer(image.read())
        if result.get('Status') != 'Upload successed.':
            return Response(status=400)
        image_url = result.get('Remote file_id')

        # 入库图片
        # sku_image.image = image_url
        # sku_image.sku_id = sku_id
        # sku_image.save()
        SKUImage.objects.filter (id=sku_image.id).update (image=image_url, sku_id=sku_id)

        # 返回响应
        return Response(status=201)


# 2,sku获取
class SKUSimpleView(ListAPIView):
    serializer_class = sku_images_serializer.SKUSimpleSerializer
    queryset = SKU.objects.order_by("id").all
